home *** CD-ROM | disk | FTP | other *** search
- Path: pegasus.montclair.edu!harmon
- From: harmon@pegasus.montclair.edu (Derek Harmon)
- Newsgroups: comp.lang.c
- Subject: Re: Ability to locate spaces?
- Date: 16 Feb 1996 01:06:54 -0500
- Organization: Montclair State University
- Message-ID: <harmon.824449354@pegasus.montclair.edu>
- References: <Pine.SOL.3.91.960215222301.15979A-100000@teer1.acpub.duke.edu>
- NNTP-Posting-Host: pegasus.montclair.edu
- X-Newsreader: NN version 6.5.0 #68 (NOV)
-
- John Young Oh <jyo@acpub.duke.edu> writes:
-
- >I would like the program to be able to recognize that there are spaces
- >between the numbers and keep track of them. What I did was to use
- >fgets and read in the line into a string. I then used a for loop
- >and checked each array element of the character string and used an
- >if statement to see if an array element was a space.
-
- Another alternative might be to check out strchr() in <string.h>.
-
- >FILE *input;
- >char *string, buf[200];
- ^ At this point, string is an uninitialized pointer, and buf is, when used
- without square brackets, effectively a pointer to a statically allocated
- 200 bytes.
-
- >int i, count;
- >input = fopen ("data", "r");
- ^ best to test fopen()'s return value with NULL to make certain everything
- has gone well.
-
- >(etc etc etc)
- ^ this should've caused some type of syntax error. :D
-
- >string = fgets (buf, 199, input);
- ^ BANG! Unless you snuck a string = (char *)malloc( ... somewhere before
- this point, string remains an uninitialized pointer. It's worth noting that
- fgets() returns the same string that it reads into buf. There is no reason
- to keep its return value here, and you could discard it with,
- : fgets(buf, 200, input); /* You don't use buf as a string, so you are */
- : /* technically allowed all 200 bytes if you */
- : /* don't intend to (otherwise buf[199] = '\0' */
- : /* is a good idea). */
-
- >for (i = 0; i < 40; ++i)
- >{
- > if (buf[i] == ' ')
- > {
- > ++count;
- > }
- >}
- ^ initializing count to zero is always prudent, although it it is statically
- declared globally you could rely on the compiler (but not if it is within a
- function). Best advice, initialize count = 0; This routine will count the
- spaces in the first forty bytes of buf[]. The braces here are also super-
- fluous, they aren't needed to envelope single statements, but that's purely
- a stylistic point.
-
- But, all told, looks like another victim of the viscious Uninitialized
- Pointer (and the tragic thing is you don't appear to need string for any-
- thing). :)
- -- Stone
- --
- # Derek Harmon (aka Stonelight) harmon@pegasus.montclair.edu
- # - Computer Science Undergrad, Montclair State University, NJ
- # - My views are my own, nobody else is this creative. 3;)>
- ... SYNTAX? Why not, they already tax everything else!
-
-